package servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;

/**
 * Servlet implementation class AlterStudentServlet
 */
public class DownloadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;


    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String filename = request.getParameter("Name");
// GET请求中，参数中包含中文需要自己动手来转换。
        String filepath = this.getServletContext().getRealPath("/uploads/" + filename);
        File file = new File(filepath);
        if(!file.exists()) {
            response.getWriter().print("您要下载的文件不存在！");
            return;
        }
// 所有浏览器都会使用本地编码，即中文操作系统使用GBK
// 浏览器收到这个文件名后，会使用iso-8859-1来解码
        filename = new String(filename.getBytes("GBK"), StandardCharsets.ISO_8859_1);
        response.addHeader("content-disposition", "attachment;filename=" + filename);
        IOUtils.copy(new FileInputStream(file), response.getOutputStream());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
